<template>
<div>
    <!--搜索栏-->
    <el-form :inline="true" :model="formInline" class="user-search">
        <el-form-item label="搜索：">
            <el-input size="small" v-model="formInline.foodName" placeholder="菜品名称"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button size="small" type="primary" icon="el-icon-search" @click="getData">搜索</el-button>
        </el-form-item>
    </el-form>

    <!--列表-->
    <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
        <el-table-column sortable prop="foodName" label="菜品名称">
            <template slot-scope="scope"><span :style="scope.row.amount <=  scope.row.warningAmount ? 'color: red;font-weight: bold;' : ''">{{scope.row.foodName}}</span></template>
        </el-table-column>
        <el-table-column sortable prop="amount" label="剩余数量">
            <template slot-scope="scope"><span :style="scope.row.amount <=  scope.row.warningAmount ? 'color: red;font-weight: bold;' : ''">{{scope.row.amount}}</span></template>
        </el-table-column>
        <el-table-column sortable prop="price" label="菜品价格">
            <template slot-scope="scope"><span :style="scope.row.amount <=  scope.row.warningAmount ? 'color: red;font-weight: bold;' : ''">{{scope.row.price}}</span></template>
        </el-table-column>
        <el-table-column sortable prop="warningAmount" label="警戒数值">
            <template slot-scope="scope"><span :style="scope.row.amount <=  scope.row.warningAmount ? 'color: red;font-weight: bold;' : ''">{{scope.row.warningAmount}}</span></template>
        </el-table-column>

      <el-table-column sortable prop="warningAmount" label="配方">
        <template slot-scope="scope"><span :style="scope.row.amount <=  scope.row.warningAmount ? 'color: red;font-weight: bold;' : ''">{{scope.row.formula}}</span></template>
      </el-table-column>
        <el-table-column align="center" label="操作">
            <template slot-scope="scope">
                <el-button size="mini" type="success" @click="handleAddFood(scope.$index, scope.row)">添加</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="addFormVisible" width="50%" @click="closeDialogAdd">
        <el-form label-width="120px" :model="addForm" ref="addForm">
            <el-form-item label="菜品名称" :rules="rules" prop="foodName">
                <el-input v-model="addForm.foodName" readonly="readonly"></el-input>
            </el-form-item>
            <el-form-item label="增加数量" prop="addAmount">
                <el-input v-model="addForm.addAmount"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button size="small" @click="closeDialogAdd">取消</el-button>
            <el-button size="small" type="primary" :loading="loading" class="title" @click="submitFormAdd('addForm')">提交</el-button>
        </div>
    </el-dialog>
</div>
</template>

<script>
import * as api from '../../api/interface'
import Pagination from '../../components/Pagination'
export default {
    data() {
        return {
            loading: false, //是显示加载
            editFormVisible: false, //控制编辑页面显示与隐藏
            addFormVisible: false,
            title: '',
            editForm: {},
            addForm: {},
            // rules表单验证
            rules: {
                addAmount: [{ required: true, message: '请输入数量', trigger: 'blur' }],
            },
            //查询条件
            formInline: {
                page: 1, //当前页面
                limit: 10, //每页数量
                foodName: ''
            },
            // 删除部门
            seletedata: {
                ids: '',
                token: localStorage.getItem('logintoken')
            },
            userparm: [], //搜索权限
            listData: [], //用户数据
            // 分页参数
            pageparm: {
                currentPage: 1,
                pageSize: 10,
                total: 10
            },
            userType: "",
            uploadFileUrl: api.uploadFileUrl,
            showUrl: api.showUrl
        }
    },
    // 注册组件
    components: {
        Pagination
    },
    /**
     * 页面初始化方法
     */
    created() {
        this.userType = localStorage.getItem("userType");
        console.log(this.$store.state.userInfo)
        this.getData()
    },
    methods: {
        // 获取列表数据
        getData() {
            this.loading = true
            let para = {
                current: this.formInline.page,
                size: this.formInline.limit,
                foodName: this.formInline.foodName
            }
            api.queryFoodByPage(para).then(data => {
                this.logining = false;
                if (data.message != "success") {
                    this.logining = false;
                    this.$message.error(data.message)
                } else {
                    this.loading = false
                    this.listData = data.returnPage.records
                    this.listData.forEach(food=>{
                      food.formula = "";
                      if(food.foodFormulaList && food.foodFormulaList.length >0){
                        food.foodFormulaList.forEach(item=>{
                          food.formula += item.materialName + "数量:"+ item.amount + ",";
                        })
                        food.formula = food.formula.substring(0,food.formula.length -1);
                      }
                    })
                    this.pageparm.currentPage = data.returnPage.current
                    this.pageparm.pageSize = data.returnPage.size
                    this.pageparm.total = data.returnPage.total
                }
            }).catch(e => {
                this.logining = false;
            });
        },
        // 分页插件事件
        callFather(parm) {
            this.formInline.page = parm.currentPage
            this.formInline.limit = parm.pageSize
            this.getData()
        },
        //显示添加界面
        handleAdd: function (index, row) {
            this.editFormVisible = true
            this.title = '新增'
            this.editForm = {}
        },
        //显示编辑界面
        handleEdit: function (index, row) {
            this.editFormVisible = true
            this.title = '编辑'
            this.editForm = row
        },
        //显示添加食品界面
        handleAddFood: function (index, row) {
            this.addFormVisible = true
            this.addForm = row
        },

        // 关闭编辑
        closeDialog() {
            this.editFormVisible = false
        },
        // 关闭添加菜品
        closeDialogAdd() {
            this.addFormVisible = false
        },
        // 编辑、增加页面保存方法
        submitForm(editData) {
            this.$refs[editData].validate(valid => {
                if (valid) {
                    let para = Object.assign({}, this.editForm);
                    this.loading = true;
                    api.updateFood(para)
                        .then(res => {
                            this.loading = false;
                            if (res.message == 'success') {
                                this.$message({ message: "提交成功", type: "success" });
                                this.getData();
                                this.editFormVisible = false;
                            } else {
                                this.$message({ type: 'error', message: res.message })
                            }
                        })
                        .catch(e => {
                            // this.editFormVisible = false
                            this.loading = false
                        })
                } else {
                    return false
                }
            })
        },
        submitFormAdd(editData) {
            this.$refs[editData].validate(valid => {
                if (valid) {
                    let para = Object.assign({}, this.addForm);
                    para.amount = parseInt(para.amount) + parseInt(para.addAmount);
                    this.loading = true;
                    api.updateFood(para)
                        .then(res => {
                            this.loading = false;
                            if (res.message == 'success') {
                                this.$message({ message: "提交成功", type: "success" });
                                let params = {
                                    userId: localStorage.getItem("userId"),
                                    userName: localStorage.getItem("userName"),
                                    userType: '2',
                                    foodId: para.foodId,
                                    foodName: para.foodName,
                                    price: para.price,
                                    amount: para.addAmount,
                                    totalPrice: para.price * para.addAmount,
                                    percentMoney: (para.percent2 * para.price * para.addAmount).toFixed(2)
                                }
                                api.updateSaleLog(params)
                                    .then(res => {
                                        this.loading = false;
                                        if (res.message == 'success') {
                                            this.$message({ message: "提交成功", type: "success" });
                                            this.getData();
                                            this.addFormVisible = false;
                                        } else {
                                            this.$message({ type: 'error', message: res.message })
                                        }
                                    })
                                    .catch(e => {
                                        // this.editFormVisible = false
                                        this.loading = false
                                    })
                                this.getData();
                                this.addFormVisible = false;
                            } else {
                                this.$message({ type: 'error', message: res.message })
                            }
                        })
                        .catch(e => {
                            // this.editFormVisible = false
                            this.loading = false
                        })
                } else {
                    return false
                }
            })
        },
        // 删除
        handleDel(index, row) {
            this.$confirm('确定要删除吗?', '信息', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
                .then(() => {
                    let para = {
                        userId: row.userId
                    }
                    api.delFood(para)
                        .then(res => {
                            if (res.message == 'success') {
                                this.$message({ message: "删除成功", type: "success" });
                                this.getData();
                            } else {
                                this.$message({ type: 'error', message: res.message })
                            }
                        })
                        .catch(e => {
                            this.loading = false
                        })
                });
        },
        handleAvatarSuccess(res, file) {
            this.editForm.imgPath = res.returnObj;
            this.$forceUpdate();
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === "image/jpeg";
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error("上传头像图片只能是 JPG 格式!");
            }
            if (!isLt2M) {
                this.$message.error("上传头像图片大小不能超过 2MB!");
            }
            return isJPG && isLt2M;
        },
    }
}
</script>

<style scoped>
.user-search {
    margin-top: 20px;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
